/**
 * Created by MyPC on 2017/6/21.
 */
var express = require('express');
var path = require('path');
var moment = require('moment');
var router = express.Router();
var multiparty = require('multiparty');
var fs = require('fs');
let fileUtil = require('./fileUtil');

router.post('/', function (req, res, next) {
  //生成multiparty对象，并配置上传目标路径
  var filePath = path.join(__dirname, '../../public/files/', moment().format('YYYYMMDD'),'/');
  console.log(filePath)
  fileUtil.mkdir(filePath);
  var form = new multiparty.Form({uploadDir: filePath});
  form.maxFilesSize = 10 * 1024 * 1024;
  //上传完成后处理
  form.parse(req, function(err, fields, files) {
    console.dir(fields)
    Object.keys(fields).forEach(function(name) {
      console.log('got field named ' + name);
    });

    if(err){
      console.log('parse error: ' + err);
    } else {
      var inputFile = files.file[0];
      let suffix = inputFile.originalFilename.substring(inputFile.originalFilename.indexOf('.'));
      console.dir(inputFile)
      if('.png|.jpg|.jpeg|.gif|.bmp'.indexOf(suffix.toLowerCase())==-1){
        console.log('不合法文件');
        res.json({result: 0, msg: '不合法文件'})
        return;
      }
      let uploadedPath = inputFile.path;
      console.log(uploadedPath)
      uploadedPath = uploadedPath.substring(uploadedPath.indexOf('public')+6);
      res.json({result: 1, msg: 'success', data: uploadedPath})
    }
  });
})

module.exports = router;